package repository

import (
	"context"
	"webook/internal/domain"
	"webook/internal/repository/dao"
)

type JobRepository interface {
	Preempt(ctx context.Context) (domain.Job, error)
	Release(ctx context.Context, id int64) error
	UpdateUtime(ctx context.Context, id int64) error
	UpdateNextTime(ctx context.Context, id int64, time int64) error
}

type PreemptJobRepository struct {
	dao dao.JobDAO
}

func NewPreemptJobRepository(dao dao.JobDAO) JobRepository {
	return &PreemptJobRepository{
		dao: dao,
	}
}

func (repo *PreemptJobRepository) UpdateNextTime(ctx context.Context, id int64, time int64) error {
	return repo.dao.UpdateNextTime(ctx, id, time)
}

func (repo *PreemptJobRepository) Release(ctx context.Context, id int64) error {
	return repo.dao.Release(ctx, id)
}

func (repo *PreemptJobRepository) Preempt(ctx context.Context) (domain.Job, error) {
	job, err := repo.dao.Preempt(ctx)
	if err != nil {
		return domain.Job{}, err
	}
	return domain.Job{
		Id:       job.Id,
		Name:     job.Name,
		Expr:     job.Expr,
		Executor: job.Executor,
	}, nil
}

func (repo *PreemptJobRepository) UpdateUtime(ctx context.Context, id int64) error {
	return repo.dao.UpdateUtime(ctx, id)
}
